import chartOp from '@/common/chart-option.js';
import echartUtil from '@/components/common/echart/echart-util.js';
import {
  clone, convertValue,
  getColor, getSerieColor, getThemeColors,
  getTooltipMarker, isNum,
  numFormat,
  xssFilter,
  mergeColorBoard,
} from '@/utils/util';
import optionList from './chart-option.json';
import _colorBoard from './color_board.js';
const colorBoard = mergeColorBoard(_colorBoard);

const tooltip = {
  seriesNameColor: '',
  backgroundColor: '',
  valueColor: '',
  componentStyle: '',
};

/**
 * 设置图表数据 series legend等
 * @param {*} option 图表option
 * @param {*} data 图表数据
 * @param {*} property 配置页面中属性面板中的参数
 */
function setChartData(option, data, property) {
  const { xAxisData, seriesData } = data;
  const { componentStyle, legend, lineType, color } = property;
  option.xAxis.data = xAxisData;

  const themeColors = getThemeColors(color, colorBoard[componentStyle].colorGroup);
  const colorGroupLength = themeColors.length;

  seriesData.forEach((item, index) => {
    const themeColor = themeColors[index % colorGroupLength];
    let serie;
    if (item.type === 'line') {
      serie = {
        type: 'line',
        name: item.name,
        data: item.data,
        symbol: 'circle',
        symbolSize: 6,
        yAxisIndex: 1,
        smooth: String(lineType) === 'fillet' ? true : false, // 线是否平滑
        // 折线拐点标志的样式
        itemStyle: { color: themeColor[0] },
        _yzName: item._yzName,
      };
    } else {
      serie = {
        type: 'bar',
        name: item.name,
        data: item.data,
        yAxisIndex: 0,
        itemStyle: { color: themeColor[0] },
        _yzName: item._yzName,
      };
    }

    // 颜色套餐
    let colorValue;
    if (typeof color === 'string') {
      colorValue = getSerieColor(themeColor);
    } else {
      colorValue = getSerieColor(getColor(color, item.name));
    }
    serie.itemStyle = { color: colorValue };

    item.name &&
      option.legend.data.push({
        icon: item.type === 'bar' ? 'rect' : 'circle',
        name: item.name,
        _yzName: item._yzName,
      });
    option.series.push(serie);
  });

  if (!legend) {
    option.legend.show = false;
  }
}

const _convertYZ = params => {
  const { xAxisData, data, dataObj, count, seriesData, emptyName } = params;
  const yzArr = ['y', 'z'];

  for (let index = 0; index < xAxisData.length; index++) {
    const x = xAxisData[index];
    const tempItem = data.find(d => String(d.x) === String(x));
    const orgData = JSON.stringify(tempItem || {});

    yzArr.forEach(yz => {
      for (let i = 0; i < count[yz]; i++) {
        let temp = tempItem[`${yz}${i + 1}`];
        if (emptyName !== 'tomographic') {
          temp = isNum(temp) ? Number(temp) : 0;
        }
        if (temp !== null) {
          dataObj[`${yz}${i}Data`].flag = true;
        }
        dataObj[`${yz}${i}Data`].data.push([x, temp, orgData]);
      }
    });
  }

  for (let i = 0; i < count.y; i++) {
    dataObj[`y${i}Data`].flag &&
    seriesData.push({
      name: dataObj[`y${i}Data`].legendName,
      type: 'bar',
      data: dataObj[`y${i}Data`].data,
      _yzName: `y${i + 1}`,
    });
  }
  for (let j = 0; j < count.z; j++) {
    dataObj[`z${j}Data`].flag &&
    seriesData.push({
      name: dataObj[`z${j}Data`].legendName,
      type: 'line',
      data: dataObj[`z${j}Data`].data,
      _yzName: `z${j + 1}`,
    });
  }
};

/**
 * 自定义图表提示框
 * @param {*} params  echart自带参数
 */
function formateTooltip(params) {
  if (!chartOp.isOrgTooltipVisible()) {
    return '';
  }
  const { seriesNameColor, componentStyle } = tooltip;
  let formatStr = '<div style="padding:5px 7px">';
  params.forEach((item, index) => {
    xssFilter(item, ['axisValue', 'seriesName', 'value']);
    if (index === 0) {
      formatStr += `<span>${echartUtil.getXaxisValue(item)}</span><br/>`;
    }

    const marker = getTooltipMarker(item.color);
    formatStr += `${marker} <span style='color:${seriesNameColor}'>${item.seriesName}:</span> ${numFormat(
      item.value[1],
      true,
    )}`;

    if (index !== params.length) {
      formatStr += '<br/>';
    }
  });
  formatStr += '<div/>';
  return formatStr;
}

/**
 * 将接口数据转换为echart方便使用的数据
 * @param {*} data 接口数据
 */
export const convertData = function(data, configData, { echart, emptyDisp }) {
  const emptyName = echart ? echart.series._emptyName : emptyDisp;
  if (!data.length) {
    return false;
  }

  const seriesData = [];
  const xAxisData = [];
  let count = { y: 0, z: 0 };
  data.forEach(item => {
    if (!xAxisData.includes(item.x)) {
      xAxisData.push(item.x);
    }
    let y = 0;
    let z = 0;
    Object.keys(item).forEach(key => {
      if (key.match(/^y\d+$/)) {
        y++;
      } else if (key.match(/^z\d+$/)) {
        z++;
      } else {}
    });
    count = {
      y: y > count.y ? y : count.y,
      z: z > count.z ? z : count.z,
    };
  });

  // 初始化数组
  const dataObj = {};
  for (let i = 0; i < count.y; i++) {
    const row = configData.tableData[i + 1];
    dataObj[`y${i}Data`] = {
      legendName: row?.legendName || `Serie_${i + 1}`,
      data: [],
      flag: false,
    };
  }
  for (let j = 0; j < count.z; j++) {
    const row = configData.tableData[count.y + 1 + j];
    dataObj[`z${j}Data`] = {
      data: [],
      legendName: row?.legendName || `Serie_${count.y + 1 + j}`,
      flag: false,
    };
  }

  _convertYZ({ xAxisData, data, dataObj, count, seriesData, emptyName });

  if (seriesData.length === 0) {
    return -1;
  }
  return { xAxisData, seriesData };
};

/**
 * 设置图表整体option
 * @param {*} data 图表数据
 * @param {*} property 配置页面中属性面板中的参数
 */
export const setChartOption = (data, property, configData) => {
  const { xAxisName = '', componentStyle, barWidth = 10 } = property;
  const { originTooltipSetting } = property.tooltip || {};
  tooltip.seriesNameColor = colorBoard[componentStyle].tooltip.seriesNameColor;
  tooltip.componentStyle = componentStyle;

  const tooltipBgColor =
    (originTooltipSetting && originTooltipSetting.background) || colorBoard[componentStyle].tooltip.backgroundColor;
  const vars = {
    componentStyle,
    colorBoard,
    xAxisName,
    formateTooltip,
    tooltipBgColor,
    xLabelRotate: property.xLabelRotate || 0,
    barWidth: convertValue(barWidth),
  };
  let option = clone(optionList);
  option = chartOp.parseJsonOption(option, vars);

  chartOp.setDataZoom('biaxial-line-bar', { option, data, property, colorBoard });
  setChartData(option, data, property);
  chartOp.setYAxisName('biaxial-line-bar', { option, property, colorBoard });
  chartOp.setMarkLine('biaxial-line-bar', { option, property, configData, colorBoard });

  // 附加公共配置
  option = chartOp.mergeOption(option, property);

  return option;
};
